const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

let snake = [{ x: 10, y: 10 }];
let direction = { x: 0, y: 0 };
let food = { x: Math.floor(Math.random() * 40) + 5, y: Math.floor(Math.random() * 40) + 5 };

document.addEventListener('keydown', changeDirection);

function createGrid() {
    ctx.fillStyle = '#ddd';
    for (let i = 0; i < 500; i += 10) {
        ctx.fillRect(i, 0, 10, 25);
        ctx.fillRect(0, i, 25, 10);
        ctx.fillRect(i, 480, 10, 25);
        ctx.fillRect(480, i, 25, 10);
    }
}

function createSnake() {
    ctx.fillStyle = 'green';
    for (let segment of snake) {
        ctx.fillRect(segment.x * 10, segment.y * 10, 10, 10);
    }
}

function createFood() {
    ctx.fillStyle = 'red';
    ctx.fillRect(food.x * 10, food.y * 10, 10, 10);
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    createGrid();
    createSnake();
    createFood();

    let headX = snake[0].x + direction.x;
    let headY = snake[0].y + direction.y;

    if (headX === food.x && headY === food.y) {
        snake.push({ x: headX, y: headY });
        food = { x: Math.floor(Math.random() * 40) + 5, y: Math.floor(Math.random() * 40) + 5 };
    } else {
        snake.shift();
    }

    if (headX < 1 || headX > 39 || headY < 1 || headY > 39 || snake.some(segment => segment.x === headX && segment.y === headY)) {
        alert('Game Over!');
        return;
    }

    snake.unshift({ x: headX, y: headY });

    requestAnimationFrame(draw);
}

function changeDirection(event) {
    const keyPressed = event.keyCode;

    if (keyPressed === 37 && direction.x !== 1) { // 左
        direction = { x: -1, y: 0 };
    } else if (keyPressed === 38 && direction.y !== 1) { // 上
        direction = { x: 0, y: -1 };
    } else if (keyPressed === 39 && direction.x !== -1) { // 右
        direction = { x: 1, y: 0 };
    } else if (keyPressed === 40 && direction.y !== -1) { // 下
        direction = { x: 0, y: 1 };
    }
}

createSnake();
draw();
